package org.ssp.util;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.junit.Test;
import org.ssp.pojo.User;



public class XML2Obj2XML {
    /**
     * 
     * obj to xml to obj
     * @param paramaters
     * @return
     */
	public static String Obj2XML(SortedMap<Object, Object> paramaters){
		StringBuffer sb=new StringBuffer();
		sb.append("<xml>");
		Set es=paramaters.entrySet();
		Iterator it=es.iterator();
		while(it.hasNext()){
			Map.Entry entry=(Map.Entry)it.next();
			String k=(String)entry.getKey();
			String v=(String)entry.getValue();
			if("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k)){
                sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
			}else{
                sb.append("<"+k+">"+v+"</"+k+">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}
	
	public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code
                + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
    }
	@Test
	public void test2(){
		System.out.println(setXML("SUCCESS","OK"));
		
	}
	  /**
		 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
		 * @param strxml
		 * @return
		 * @throws JDOMException
		 * @throws IOException
		 */
		public static Map doXMLParse(String strxml) throws Exception {
			if(null == strxml || "".equals(strxml)) {
				return null;
			}
			
			Map m = new HashMap();
			InputStream in = String2Inputstream(strxml);
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(in);
			Element root = doc.getRootElement();
			List list = root.getChildren();
			Iterator it = list.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String k = e.getName();
				String v = "";
				List children = e.getChildren();
				if(children.isEmpty()) {
					v = e.getTextNormalize();
				} else {
					v = getChildrenText(children);
				}
				m.put(k, v);
			}
			
			//关闭流
			in.close();
			return m;
		}
		/**
		 * 获取子结点的xml
		 * @param children
		 * @return String
		 */
		public static String getChildrenText(List children) {
			StringBuffer sb = new StringBuffer();
			if(!children.isEmpty()) {
				Iterator it = children.iterator();
				while(it.hasNext()) {
					Element e = (Element) it.next();
					String name = e.getName();
					String value = e.getTextNormalize();
					List list = e.getChildren();
					sb.append("<" + name + ">");
					if(!list.isEmpty()) {
						sb.append(getChildrenText(list));
					}
					sb.append(value);
					sb.append("</" + name + ">");
				}
			}
			return sb.toString();
		}
	public static InputStream String2Inputstream(String str) {
		ByteArrayInputStream bin=null;
			try {
				 bin=new ByteArrayInputStream(str.getBytes("utf-8"));//xml的编码格式转为utf-8
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return bin;
	}
	@Test
	public void test(){
		Map mp=null;
		String xml2="<xml>"+
				   "<return_code><![CDATA[SUCCESS]]></return_code>"+
				   "<return_msg><![CDATA[OK]]></return_msg>"+
				   "<appid><![CDATA[wx2421b1c4370ec43b]]></appid>"+
				   "<mch_id><![CDATA[10000100]]></mch_id>"+
				   "<nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>"+
				   "<sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>"+
				   "<result_code><![CDATA[SUCCESS]]></result_code>"+
				   "<prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>"+
				   "<trade_type><![CDATA[JSAPI]]></trade_type>"+
				   "</xml>";
		String xml="<xml>"+
					"<appid>wx2421b1c4370ec43b</appid>"+
					"<attach><![CDATA[att1]]></attach>"+
					"<body><![CDATA[JSAPI]]></body>"+
					"<device_info>1000</device_info>"+
					"<mch_id>10000100</mch_id>"+
					"<nonce_str>b927722419c52622651a871d1d9ed8b2</nonce_str>"+
					"<notify_url>http://wxpay.weixin.qq.com/pub_v2/pay/notify.php</notify_url>"+
					"<out_trade_no>1405713376</out_trade_no>"+
					"<spbill_create_ip>127.0.0.1</spbill_create_ip>"+
					"<total_fee>1</total_fee>"+
					"<trade_type>JSAPI</trade_type>"+
					"<sign><![CDATA[3CA89B5870F944736C657979192E1CF4]]></sign>"+
					"</xml>";
		try {
			 mp=doXMLParse(xml2);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(mp.get("appid"));
	}
}
